﻿namespace Xms.Abp.Components;

public partial class NNameValueDataSourceSelect<TNameValueService> : Select<Guid?, NameValue<Guid?>>
    where TNameValueService : class, INameValueService<Guid>
{
    public NNameValueDataSourceSelect()
    {
        LabelName = nameof(NameValue<Guid>.Name);
        ValueName = nameof(NameValue<Guid>.Value);
        EnableSearch = true;
    }
    //protected IEnumerable<NameValue<Guid>> DataSource;

    //[Parameter] public Guid? Value { get; set; }
    //[Parameter] public bool Disabled { get; set; }
    //[Parameter] public bool AllowClear { get; set; }
    //[Parameter] public RenderFragment PrefixIcon { get; set; }
    //[Parameter] public string Size { get; set; }
    //[Parameter] public string Placeholder { get; set; }

    [Inject] public TNameValueService NameValueService { get; set; }

    [Parameter] public string NullLabel { get; set; } = "请选择";

    protected override async Task OnInitializedAsync()
    {
        if (DataSource == null)
        {
            var list = await NameValueService.GetNNameValuesAsync();
            if (!NullLabel.IsNullOrWhiteSpace())
            {
                list.Insert(0, new NameValue<Guid?>
                {
                    Name = NullLabel,
                    Value = null
                });
            }
            DataSource = list;
        }
        if (EnableSearch && !Disabled)
        {
            OnSearch = async filter => await OnSearchAsync(filter);
        }
        await base.OnInitializedAsync();
    }

    protected async Task OnSearchAsync(string filter)
    {
        var list = await NameValueService.GetNNameValuesAsync(filter);
        if (!NullLabel.IsNullOrWhiteSpace())
        {
            list.Insert(0, new NameValue<Guid?>
            {
                Name = NullLabel,
                Value = null
            });
        }
        DataSource = list;
    }
}
